package com.learning.servlet3x.annotation;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * ClassName: CustomFilter
 * Description: Servlet3x新特性：使用注解取代标签配置
 * Date:  2014/12/06 16:32 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@WebFilter(filterName = "CustomFilter", urlPatterns = "/filter/*", servletNames = {"CustomServlet"},
        dispatcherTypes = DispatcherType.REQUEST,
        initParams = {
                @WebInitParam(name = "user", value = "sam"),
                @WebInitParam(name = "sex", value = "男")
        })
public class CustomFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter 自定义参数 user: " + filterConfig.getInitParameter("user"));
        System.out.println("Filter 自定义参数 sex: " + filterConfig.getInitParameter("sex"));
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        System.out.println("监听到访问了：" + req.getRequestURL());
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}

/*
    相当于web.xml配置:
    <filter>
        <filter-name>CustomFilter</filter-name>
        <filter-class>com.learning.servlet3x.annotation.CustomFilter</filter-class>
        <init-param>
            <param-name>user</param-name>
            <param-value>Sam</param-value>
        </init-param>
        <init-param>
            <param-name>sex</param-name>
            <param-value>sex</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CustomFilter</filter-name>
        <url-pattern>/filter/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <servlet-name>CustomServlet</servlet-name>
    </filter-mapping>
*/
